import PropTypes from 'prop-types';
import React, { useContext, useState } from 'react';
import { Box, Grid, Tab, Tabs, Typography, Button } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import useConfig from 'hooks/useConfig';
import WorkflowContext from 'contexts/WorkflowContext';

function TabPanel({ children, value, index, ...other }) {
  return (
    <div role="tabpanel" hidden={value !== index} id={`vertical-tabpanel-${index}`} aria-labelledby={`vertical-tab-${index}`} {...other}>
      {value === index && <Box sx={{ p: 0 }}>{children}</Box>}
    </div>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired
};

function a11yProps(index) {
  return {
    id: `vertical-tab-${index}`,
    'aria-controls': `vertical-tabpanel-${index}`
  };
}

function reorganizeArrayData(arr) {
  const results = [];
  const resultMap = {
    trigger: {
      label: '触发',
      description: '用于事件的触发',
      buttons: []
    },
    executive: {
      label: '执行',
      description: '事件触发后的执行',
      buttons: []
    }
  };

  arr.forEach(({ name, nameCn, type }) => {
    if (resultMap[type]) {
      resultMap[type].buttons.push({
        text: nameCn,
        name
      });
    }
  });

  // 修改部分: 使用 Object.keys 遍历对象，增加了对原型链属性的过滤
  Object.keys(resultMap).forEach((type) => {
    if (Object.prototype.hasOwnProperty.call(resultMap, type)) {
      results.push(resultMap[type]);
    }
  });

  return results;
}

const tabsStyles = (theme) => ({
  '& .MuiTabs-flexContainer': { borderBottom: 'none' },
  '& button': {
    borderRadius: theme.borderRadius,
    color: theme.palette.mode === 'dark' ? 'grey.600' : 'grey.900',
    minHeight: 'auto',
    minWidth: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'flex-start',
    textAlign: 'left',
    justifyContent: 'flex-start'
  },
  '& button.Mui-selected': {
    color: theme.palette.primary.main,
    background: theme.palette.mode === 'dark' ? theme.palette.dark.main : theme.palette.grey[50]
  }
});

export default function SelectModule({ onModuleSelected }) {
  const { allModules } = useContext(WorkflowContext);
  const theme = useTheme();
  const [value, setValue] = useState(0);

  const handleChange = (event, newValue) => setValue(newValue);
  const moduleData = reorganizeArrayData(allModules);

  const handleButtonClick = async (button) => {
    if (onModuleSelected) {
      onModuleSelected(button.name);
    }
  };
  return (
    <div>
      <Grid container>
        <Grid item>
          <Tabs value={value} onChange={handleChange} orientation="vertical" variant="scrollable" sx={tabsStyles(theme)}>
            {moduleData.map((tab, index) => (
              <Tab
                key={tab.label}
                label={
                  <Grid container direction="column">
                    <Typography variant="subtitle1">{tab.label}</Typography>
                    <Typography component="div" variant="caption" sx={{ textTransform: 'capitalize' }}>
                      {tab.description}
                    </Typography>
                  </Grid>
                }
                {...a11yProps(index)}
              />
            ))}
          </Tabs>
        </Grid>
        <Grid item>
          {moduleData.map((tab, index) => (
            <TabPanel key={tab.label} value={value} index={index}>
              {tab.buttons.map((button) => (
                <Button key={button.name} onClick={() => handleButtonClick(button)}>
                  {button.text}
                </Button>
              ))}
            </TabPanel>
          ))}
        </Grid>
      </Grid>
    </div>
  );
}
